import json

from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse
from .models import *
import jwt
# Create your views here.

#为空
def is_empty(a):
    return a is None or str(a).strip()==""

#登录
@csrf_exempt
@require_http_methods(['POST'])
def login(request):
    data=json.loads(request.body)
    username=data['username']
    password=data['password']

    if User.objects.filter(username=username).exists()==False:
        return JsonResponse({
            'msg' : '此用户未注册'
        })
    p=User.objects.get(username=username)
    if password!=p.password:
        return JsonResponse({
            'msg' : '密码不正确'
        })

    mi='123456'
    pay={'username':p.username,'password':p.password}
    token=jwt.encode(pay,mi)
    return JsonResponse({
        'msg' : '登录成功',
        'token' : token
    })

#商品分类查询
@csrf_exempt
@require_http_methods(['GET'])
def fenlei(request):
    data=ProductCategory.objects.all()
    list=[]
    for i in data:
        list.append(model_to_dict(i))
    return JsonResponse({
        'msg':'查询成功 ',
        'data':list
    })

#商品新增
@csrf_exempt
@require_http_methods(['POST'])
def addproduct(request):
    data=json.loads(request.body)
    product_name=data['product_name']
    product_category_id = data['product_category']
    product_price = data['product_price']
    product_stock = data['product_stock']

    a=Product.objects.create(
        product_name=product_name,
        product_category_id=product_category_id,
        product_price=product_price,
        product_stock=product_stock
    )
    return JsonResponse({"msg" : "添加成功", "data" : model_to_dict(a)})

#修改
@csrf_exempt
@require_http_methods(['PUT'])
def updateproduct(request,id):
    data = json.loads(request.body)
    tt=Product.objects.get(id=id)
    tt.product_name=data['product_name']
    tt.product_category_id=data['product_category']
    tt.product_price = data['product_price']
    tt.product_stock = data['product_stock']
    tt.save()
    return JsonResponse({"msg" : "修改成功", "data" : model_to_dict(tt)})

#删除
@csrf_exempt
@require_http_methods(['DELETE'])
def deleteproduct(request,id):
    if Product.objects.filter(id=id).exists()==False:
        return JsonResponse({
            'msg':'此订单删除不了'
        })
    Product.objects.get(id=id).delete()
    return JsonResponse({"msg" : "删除成功"})

#分页查询
@csrf_exempt
@require_http_methods(['GET'])
def fenye(request) :
    # token=request.META.get('HTTP_TOKEN')
    # if not token :
    #     return JsonResponse({
    #         'msg' : '请先登录'
    #     })
    # try:
    #     mi='123456'
    #     jwt.decode(token,mi,algorithms=["HS256"])
    # except jwt.InvalidTokenError:
    #     return JsonResponse({
    #         'msg':'token已失效'
    #     })

    data=Product.objects.all()
    product_name=request.GET.get('product_name')
    product_category_id=request.GET.get('product_category_id')
    if product_name:
        data=Product.objects.filter(product_name__contains=product_name)
    if product_category_id :
        data = Product.objects.filter(product_category_id=product_category_id)
    total=len(data)
    page=request.GET.get('page',1)
    size=request.GET.get('size') or 10
    fy=Paginator(data,size)
    data=fy.get_page(page)

    list = []
    for i in data :
        list.append(model_to_dict(i))
    return JsonResponse({
        'msg' : '查询成功',
        'data' : list,
        'total' : total
    })

@csrf_exempt
@require_http_methods(['GET'])
def lishifenye(request) :
    token=request.META.get('HTTP_TOKEN')
    if not token :
        return JsonResponse({
            'msg' : '请先登录'
        })
    try:
        mi='123456'
        jwt.decode(token,mi,algorithms=["HS256"])
    except jwt.InvalidTokenError:
        return JsonResponse({
            'msg':'token已失效'
        })

    data=Order.objects.all()

    total=len(data)
    page=request.GET.get('page',1)
    size=request.GET.get('size') or 10
    fy=Paginator(data,size)
    data=fy.get_page(page)

    list = []
    for i in data :
        list.append(model_to_dict(i))
    return JsonResponse({
        'msg' : '查询成功',
        'data' : list,
        'total' : total
    })

@csrf_exempt
@require_http_methods(['POST'])
def addorder(request):
    data=json.loads(request.body)
    order_quantity=data['order_quantity']
    order_amount = data['order_amount']
    customer_name = data['customer_name']
    product_id=data['product_id']
    user_id = data['user_id']

    a=Order.objects.create(
        order_quantity=order_quantity,
        order_amount=order_amount,
        customer_name=customer_name,
        product_id=product_id,
        user_id=user_id
    )

    return JsonResponse({"msg" : "创建成功", "data" : model_to_dict(a)})

#直接查询订单
@csrf_exempt
@require_http_methods(['GET'])
def chaxunorder(request) :
    data=Order.objects.all()
    list=[]
    for i in data:
        list.append(model_to_dict(i))
    return JsonResponse({
        'msg':'查询成功',
        'data':list
    })
